<template>
  <div class="login" :style="backgroundimage">
    <div class="loginbody">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="ruleForm.username"
            autocomplete="off"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
            v-model="ruleForm.pwd"
            autocomplete="off"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="validation" required>
          <el-col :span="16">
            <el-input
              v-model="ruleForm.validation"
              autocomplete="off"
              placeholder="输入验证码(不区分大小写)"
            ></el-input>
          </el-col>
          <el-col :span="8" align="right"
            ><Valida
              v-model="validCode"
              ref="refresh"
              @sendData="getCode"
            ></Valida
          ></el-col>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userlogin('ruleForm')"
            >立即登录</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
        <p>
          没有账号？<span
            ><router-link :to="{ name: 'register' }"
              >立即注册</router-link
            ></span
          >
        </p>
        <p><span @click="dialogFormVisible = true">忘记密码？</span></p>
      </el-form>
    </div>
    <!-- 忘记密码... -->
    <el-dialog
      title="找回密码"
      :visible.sync="dialogFormVisible"
      center
      width="35%"
    >
      <el-form
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账号/手机号" prop="loginname">
          <el-input
            v-model="form.loginname"
            autocomplete="off"
            placeholder="请输入手机号码"
          ></el-input>
        </el-form-item>
        <el-form-item label="设置新密码" prop="newpassword1">
          <el-input
            type="password"
            v-model="form.newpassword1"
            autocomplete="off"
            show-password
            placeholder="请输入新密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="newpassword2">
          <el-input
            type="password"
            v-model="form.newpassword2"
            autocomplete="off"
            show-password
            placeholder="请确定新密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitform('form')"
            >提交</el-button
          >
          <el-button @click="resetform('form')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import Valida from "@/components/Validationcode.vue";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入新密码密码"));
      } else {
        if (this.form.newpassword1 !== "") {
          this.$refs.form.validateField("newpassword2");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次确定新密码"));
      } else if (value !== this.form.newpassword1) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      validCode: "",
      ruleForm: {
        pwd: "",
        username: "",
        validation: ""
      },
      form: {
        loginname: "",
        newpassword1: "",
        newpassword2: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入账号", trigger: "blur" },
          { min: 2, message: "长度至少两个字符", trigger: "blur" }
        ],
        pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 2, message: "长度至少两个字符", trigger: "blur" }
        ],
        validation: [
          { required: true, message: "请输入验证码", trigger: "blur" }
        ],
        newpassword1: [{ validator: validatePass, trigger: "blur" }],
        newpassword2: [{ validator: validatePass2, trigger: "blur" }],
        loginname: [{ required: true, message: "请输入账号", trigger: "blur" }]
      },
      checked: false,
      dialogFormVisible: false,
      formLabelWidth: "120px",
      backgroundimage: {
        backgroundImage: "url(" + require("@/assets/images/bj.jpg") + ")",
        backgroundRepeat: "no-repeat",
        backgroundSize: "100% 100%"
      }
    };
  },
  components: {
    Valida
  },
  created() {},
  methods: {
    //获取验证码
    getCode(data) {
      this.validCode = data.split(/\W/).join('').toLowerCase(); //在data中定义一个  对data处理不区分大小写
    },
    userlogin(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.ruleForm.validation == this.validCode) {
            this.$http
              .post("/userlogin", this.ruleForm)
              .then(res => {
                // console.log(res);
                if (res.data != null) {
                  this.$message({
                    message: "登录成功",
                    type: "success"
                  });
                  sessionStorage.setItem("loginname", res.data.loginName);
                  sessionStorage.setItem("nickname", res.data.nickname);
                  sessionStorage.setItem("usericon", res.data.userIcon);
                  sessionStorage.setItem("loginpassword",res.data.loginPassword);
                  sessionStorage.setItem("id", res.data.id);
                  try {
                    if (this.$route.query.redirect) {
                      //判断是否点击登录按钮
                      let url = decodeURIComponent(this.$route.query.redirect);
                      console.log(url);
                      this.$router.push({ path: url });
                    } else {
                      this.$router.push({ path: "/" });
                      this.$router.go(0);
                    }
                  } catch (err) {
                    this.$router.push({ name: "index" });
                    this.$router.go(0);
                  }
                } else {
                  this.$message({
                    message: "账号或密码错误，请重新输入！",
                    type: "error"
                  });
                }
              })
              .catch(function() {});
          } else {
            this.$message({
              message: "验证码错误！",
              type: "error"
            });
            this.$refs.refresh.createdCode();
            this.validCode = null; //清空验证码输入框的内容
          }
        } else {
          this.$message({
            message: "信息不能为空！",
            type: "error"
          });
          this.$refs.refresh.createdCode();
        }
      });
    },
    //重置登录框
    resetForm(ruleForm) {
      this.$refs[ruleForm].resetFields();
      this.$refs.refresh.createdCode();
    },
    //找回密码
    submitform(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.$http
            .post("/userbackpassword", this.form)
            .then(res => {
              // console.log(res);
              if (res.status == 200) {
                this.$message({
                  message: "登录密码找回成功...",
                  type: "success"
                });
                this.dialogFormVisible = false;
              }
              else{
                  this.$message({
                  message: "账号不正确...",
                  type: "error"
                });
              }
            })
            .catch(function() {});
        } else {
          this.$message({
            message: "找回密码失败...",
            type: "error"
          });
        }
      });
    },
    resetform(form) {
      this.$refs[form].resetFields();
    }
  }
};
</script>

<style scoped>
.login {
  width: 100%;
}
.loginbody {
  width: 1200px;
  margin: 0 auto;
}
.el-form {
  width: 400px;
  padding: 45px;
}
p {
  display: inline;
  font-size: 16px;
  color: #606266;
  margin-left: 80px;
}
p span {
  cursor: pointer;
  color: #6295ec;
}
p span:hover {
  color: #2b57a2;
}
</style>